<template>
	<view class="add-goods-container">
		<!-- 图片上传 -->
		<view class="upload-section">
			<u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" name="goodsImage" multiple
				:maxCount="1" width="120rpx" height="120rpx">
				<view class="upload-placeholder" hover-class="upload-placeholder-hover">
					<u-icon name="plus" color="#fff" size="24"></u-icon>
					<text>{{ fileList.length ? '更换图片' : '添加图片' }}</text>
				</view>
			</u-upload>
		</view>

		<!-- 基本信息 -->
		<view class="form-item">
			<text class="form-label">条形码</text>
			<u--input class="form-input" placeholder="请输入条形码或点击扫码" placeholderStyle="color: #c0c4cc;" border="none"
				v-model="formData.barcode" fontSize="28rpx">
				<template slot="suffix">
					<u-icon name="scan" size="40rpx" @click="scanBarcode"></u-icon>
				</template>
			</u--input>
		</view>

		<view class="form-item">
			<text class="form-label required">货品名称</text>
			<u--input class="form-input" placeholder="请输入货品名称" placeholderStyle="color: #c0c4cc;" border="none"
				v-model="formData.goodsSpec" fontSize="28rpx"></u--input>
		</view>

		<view class="form-item clickable" hover-class="form-item-hover" @click="showCategoryPicker = true">
			<text class="form-label">货品类别</text>
			<view class="value-with-arrow">
				<text class="form-value">{{ formData.categoryName || '其他类别' }}</text>
				<u-icon name="arrow-right" color="#c0c4cc" size="14"></u-icon>
			</view>
		</view>

		<view class="form-item clickable" hover-class="form-item-hover" @click="showUnitPicker = true">
			<text class="form-label">主单位</text>
			<view class="value-with-arrow">
				<text class="form-value">{{ formData.unitName || '请选择' }}</text>
				<u-icon name="arrow-right" color="#c0c4cc" size="14"></u-icon>
			</view>
		</view>

		<view class="form-item">
			<text class="form-label">当前库存</text>
			<u--input class="form-input" placeholder="0.00" type="number"
				placeholderStyle="color: #c0c4cc; text-align: right;" border="none" v-model="formData.initialStock"
				fontSize="28rpx" inputAlign="right"></u--input>
		</view>

		<!-- <view class="form-item">
			<text class="form-label">安全库存</text>
			<view class="safe-stock-input">
				<u--input
					placeholder="最小"
					type="number"
					placeholderStyle="color: #c0c4cc; text-align: right;"
					border="none"
					v-model="formData.minStock"
					fontSize="28rpx"
					inputAlign="right"
					style="width: 45%;"
				></u--input>
				<text class="separator">~</text>
				<u--input
					placeholder="最大"
					type="number"
					placeholderStyle="color: #c0c4cc; text-align: right;"
					border="none"
					v-model="formData.maxStock"
					fontSize="28rpx"
					inputAlign="right"
					style="width: 45%;"
				></u--input>
			</view>
		</view> -->

		<view class="form-item">
			<text class="form-label">进货价</text>
			<u--input class="form-input" placeholder="0.00" type="number"
				placeholderStyle="color: #c0c4cc; text-align: right;" border="none" v-model="formData.purchasePrice"
				fontSize="28rpx" inputAlign="right"></u--input>
		</view>

		<view class="form-item">
			<text class="form-label">批发价</text>
			<u--input class="form-input" placeholder="0.00" type="number"
				placeholderStyle="color: #c0c4cc; text-align: right;" border="none" v-model="formData.wholesalePrice"
				fontSize="28rpx" inputAlign="right"></u--input>
		</view>

		<view class="form-item">
			<text class="form-label">零售价</text>
			<u--input class="form-input" placeholder="0.00" type="number"
				placeholderStyle="color: #c0c4cc; text-align: right;" border="none" v-model="formData.retailPrice"
				fontSize="28rpx" inputAlign="right"></u--input>
		</view>

		<view class="form-item">
			<text class="form-label">备注</text>
			<u--textarea class="form-input" placeholder="请输入备注信息" placeholderStyle="color: #c0c4cc;" border="none"
				v-model="formData.remark" fontSize="28rpx" autoHeight></u--textarea>
		</view>

		<!-- 备注下方的空白区域 -->
		<view class="remark-placeholder"></view>

		<!-- 底部操作按钮 -->
		<view class="footer-actions">
			<view class="btn-continue" hover-class="btn-continue-hover" @click="saveAndContinue">继续新增</view>
			<view class="btn-save" hover-class="btn-save-hover" @click="saveGoods">保存</view>
		</view>

		<!-- 选择器 -->
		<u-picker :show="showCategoryPicker" :columns="categoryColumns" keyName="label" @confirm="confirmCategory"
			@cancel="showCategoryPicker = false"></u-picker>
		<u-picker :show="showUnitPicker" :columns="unitColumns" keyName="label" @confirm="confirmUnit"
			@cancel="showUnitPicker = false"></u-picker>
	</view>
</template>

<script>
	import api from '@/utils/api.js'
	import {
		url
	} from '@/constant/domain.js'
	export default {
		data() {
			return {
				goodsId: null, // 商品ID，如果存在表示是编辑模式
				fileList: [], // 上传的文件列表
				formData: {
					barcode: '',
					goodsSpec: '', // 货品名称
					categoryId: null,
					categoryName: '其他类别', // 默认类别
					unitId: null,
					unitName: '',
					initialStock: '',
					minStock: '',
					maxStock: '',
					purchasePrice: '',
					wholesalePrice: '',
					retailPrice: '',
					remark: '',
					image: '' // 图片路径
				},
				showCategoryPicker: false,
				categoryColumns: [
					// 示例分类数据
					[{
						label: '其他类别',
						id: null
					}, {
						label: '测试分类A',
						id: 1
					}, {
						label: '测试分类B',
						id: 2
					}]
				],
				showUnitPicker: false,
				unitColumns: [
					// 示例单位数据
					[{
						label: '个',
						id: 1
					}, {
						label: '件',
						id: 2
					}, {
						label: '箱',
						id: 3
					}]
				],
				isEditMode: false // 是否为编辑模式
			};
		},
		onLoad(options) {
			// 初始值设置为图片中显示的值
			this.formData.remark = 'true';
			// 加载分类数据
			this.loadCategories();
			// 加载单位数据
			this.loadUnits();

			// 如果有ID参数，表示是编辑模式
			if (options.id) {
				this.goodsId = options.id;
				this.isEditMode = true;
				this.fetchGoodsDetail();
			}
		},
		methods: {
			// 获取商品详情
			fetchGoodsDetail() {
				uni.showLoading({
					title: '加载中...',
					mask: true
				});

				api.getGoodsDetail(this.goodsId).then(res => {
					if (res) {
						// 填充表单数据
						this.formData = {
							...this.formData,
							...res
						};

						// 如果有图片，添加到图片列表
						if (res.image) {
							this.fileList = [{
								url: res.image
							}];
						}
					} else {
						uni.showToast({
							title: '商品不存在',
							icon: 'none'
						});
					}
				}).catch(err => {
					console.error('获取商品详情失败:', err);
					uni.showToast({
						title: '获取商品详情失败',
						icon: 'none'
					});
				}).finally(() => {
					uni.hideLoading();
				});
			},

			// 加载分类数据
			loadCategories() {
				api.getCategoryList().then(res => {
					console.log('原始分类数据:', res);

					// 处理扁平结构的分类数据
					if (res && Array.isArray(res)) {
						// 先将所有分类转为{id -> 分类}的映射
						const categoryMap = {};
						res.forEach(item => {
							if (item && item.id) {
								// 深拷贝，确保不修改原始数据
								categoryMap[item.id] = {
									...item,
									children: []
								};
							}
						});

						// 根节点列表
						const rootCategories = [];

						// 构建树形结构
						res.forEach(item => {
							if (!item || !item.id) return;

							// 检查是否有父节点
							if (item.parentId && item.parentId !== 0 && categoryMap[item.parentId]) {
								// 将当前节点添加到父节点的children中
								categoryMap[item.parentId].children.push(categoryMap[item.id]);
							} else {
								// 没有父节点或父节点不存在，作为根节点
								rootCategories.push(categoryMap[item.id]);
							}
						});

						console.log('构建的树形结构:', rootCategories);

						// 将树形结构扁平化，用于选择器显示
						const flattenCategories = this.flattenCategoryTree(rootCategories);

						console.log('扁平化后的分类:', flattenCategories);

						// 确保有"其他类别"选项
						if (!flattenCategories.find(c => c.label === '其他类别')) {
							flattenCategories.unshift({
								label: '其他类别',
								id: null,
								categoryName: '其他类别'
							});
						}

						// 更新选择器数据
						this.categoryColumns = [
							[...flattenCategories]
						];
					} else {
						// 如果API返回的不是数组，设置默认分类
						this.categoryColumns = [
							[{
								label: '其他类别',
								id: null,
								categoryName: '其他类别'
							}]
						];
					}
				}).catch(err => {
					console.error('加载分类数据失败:', err);
					uni.showToast({
						title: '加载分类数据失败',
						icon: 'none'
					});

					// 错误情况下设置默认分类
					this.categoryColumns = [
						[{
							label: '其他类别',
							id: null,
							categoryName: '其他类别'
						}]
					];
				});
			},

			// 将树形结构扁平化
			flattenCategoryTree(tree) {
				if (!tree || !Array.isArray(tree) || tree.length === 0) {
					console.log('分类树为空');
					return [];
				}

				console.log('开始扁平化分类树，节点数:', tree.length);
				let result = [];

				// 递归处理树形结构
				const process = (items, level = 0) => {
					if (!items || !Array.isArray(items) || items.length === 0) return;

					items.forEach(item => {
						// 跳过无效数据
						if (!item || !item.categoryName) {
							console.log('跳过无效分类项', item);
							return;
						}

						// 添加当前节点（添加层级标识）
						const prefix = level > 0 ? '　'.repeat(level) + '└ ' : '';
						const categoryName = prefix + item.categoryName;

						console.log(`添加分类[L${level}]:`, categoryName);

						result.push({
							...item,
							label: categoryName, // 添加label属性供选择器使用
							categoryName: categoryName,
							originalName: item.categoryName // 保留原始名称
						});

						// 处理子节点
						if (item.children && Array.isArray(item.children) && item.children.length > 0) {
							process(item.children, level + 1);
						}
					});
				};

				process(tree);
				console.log('扁平化分类完成，共', result.length, '个分类');
				return result;
			},

			// 加载单位数据
			loadUnits() {
				// 这里应该有获取单位列表的API调用
				// 暂时使用假数据
				const units = [{
						label: '个',
						id: 1
					},
					{
						label: '件',
						id: 2
					},
					{
						label: '箱',
						id: 3
					}
				];
				this.unitColumns = [units];
			},

			// 扫描条形码
			scanBarcode() {
				// 调用扫码API
				uni.scanCode({
					scanType: ['barCode'], // 仅识别条形码
					success: (res) => {
						// 成功回调
						this.formData.barcode = res.result;
					},
					fail: (err) => {
						console.error('扫码失败:', err);
						uni.showToast({
							title: '扫码失败',
							icon: 'none'
						});
					}
				});
			},

			// 图片上传相关
			async afterRead(event) {
				const file = event.file[0];
				// 显示上传中的临时状态
				uni.showLoading({
					title: '上传中...'
				});

				// 创建上传任务
				const uploadTask = uni.uploadFile({
					url: `${url}/common/upload`, // 上传文件服务器地址
					filePath: file.url,
					name: 'file', // 服务器接收的文件参数名
					header: {
						'Authorization': `Bearer ${this.$user.getToken()}` // 添加认证信息
					},
					success: (uploadRes) => {
						// 处理返回结果
						try {
							const result = JSON.parse(uploadRes.data);
							if (result.code === 200) {
								// 上传成功，更新文件列表和表单数据
								this.fileList = [{
									url: `${url}${result.fileName}`
								}];
								this.formData.goodsImage = `${url}${result.fileName}`;
							} else {
								uni.showToast({
									title: result.msg || '上传失败',
									icon: 'none'
								});
							}
						} catch (e) {
							console.error('解析上传响应失败:', e);
							uni.showToast({
								title: '上传失败',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						console.error('上传失败:', err);
						uni.showToast({
							title: '图片上传失败',
							icon: 'none'
						});
					},
					complete: () => {
						uni.hideLoading();
					}
				});

				// 监听上传进度
				uploadTask.onProgressUpdate((res) => {
					console.log('上传进度:', res.progress);
					// 可以在这里实现进度条
				});
			},
			deletePic(event) {
				this.fileList.splice(event.index, 1);
				this.formData.image = '';
			},

			// 选择器相关
			confirmCategory(e) {
				console.log('选择分类:', e);

				const selected = e.value[0];
				if (selected) {
					// 更新选中的分类ID和名称
					this.formData.categoryId = selected.id;

					// 优先使用原始名称，没有则使用label并去除前缀
					if (selected.originalName) {
						this.formData.categoryName = selected.originalName;
					} else {
						// 移除层级前缀，只使用分类名称本身
						let displayName = selected.label;
						// 如果名称中包含前缀标记，则只取最后一部分
						if (displayName && displayName.includes('└')) {
							displayName = displayName.split('└').pop().trim();
						}
						this.formData.categoryName = displayName || '其他类别';
					}

					this.showCategoryPicker = false;

					console.log('已选择分类:', this.formData.categoryName, 'ID:', this.formData.categoryId);
				}
			},
			confirmUnit(e) {
				const selected = e.value[0];
				this.formData.unitId = selected.id;
				this.formData.unitName = selected.label;
				this.showUnitPicker = false;
			},

			// 保存逻辑
			validateForm() {
				if (!this.formData.goodsSpec) {
					uni.showToast({
						title: '请输入货品名称',
						icon: 'none'
					});
					return false;
				}
				// 可以添加更多验证规则
				return true;
			},
			saveGoods() {
				if (!this.validateForm()) return;

				uni.showLoading({
					title: '保存中...',
					mask: true // 添加遮罩防止重复点击
				});

				// 根据是否为编辑模式调用不同的API
				const savePromise = this.isEditMode ?
					api.updateGoods(this.goodsId, this.formData) :
					api.addGoods(this.formData);

				savePromise.then(res => {
					uni.hideLoading();
					uni.showToast({
						title: this.isEditMode ? '更新成功' : '保存成功',
						icon: 'success',
						duration: 1500
					});

					// 延迟返回，让用户看到成功提示
					setTimeout(() => {
						// 返回上一页
						uni.navigateBack({
							delta: 1
						});
					}, 800);
				}).catch(err => {
					uni.hideLoading();
					uni.showToast({
						title: err || (this.isEditMode ? '更新失败' : '保存失败'),
						icon: 'none',
						duration: 2000
					});
				});
			},
			saveAndContinue() {
				if (!this.validateForm()) return;

				uni.showLoading({
					title: '保存中...',
					mask: true // 添加遮罩防止重复点击
				});

				// 编辑模式下先更新，然后准备新增
				const savePromise = this.isEditMode ?
					api.updateGoods(this.goodsId, this.formData) :
					api.addGoods(this.formData);

				savePromise.then(res => {
					uni.hideLoading();
					uni.showToast({
						title: this.isEditMode ? '更新成功' : '保存成功',
						icon: 'success'
					});

					// 如果是编辑模式，成功后重置为新增模式
					if (this.isEditMode) {
						this.goodsId = null;
						this.isEditMode = false;
					}

					// 重置表单
					this.resetForm();
				}).catch(err => {
					uni.hideLoading();
					uni.showToast({
						title: err || (this.isEditMode ? '更新失败' : '保存失败'),
						icon: 'none',
						duration: 2000
					});
				});
			},
			resetForm() {
				this.fileList = [];
				this.formData = {
					barcode: '',
					name: '',
					categoryId: this.formData.categoryId, // 保留分类
					categoryName: this.formData.categoryName,
					unitId: null,
					unitName: '',
					initialStock: '',
					minStock: '',
					maxStock: '',
					purchasePrice: '',
					wholesalePrice: '',
					retailPrice: '',
					remark: 'true',
					image: ''
				};
			}
		}
	};
</script>

<style lang="scss" scoped>
	page {
		background-color: #f5f7fa;
	}

	.add-goods-container {
		min-height: 100vh;
		background-color: #f5f7fa;
		padding-top: 40rpx;
		/* 增加顶部padding防止内容被状态栏遮挡 */
		padding-bottom: 120rpx;
		position: relative;
		/* 添加相对定位 */
	}

	// 图片上传
	.upload-section {
		margin: 0 30rpx;
		margin-bottom: 20rpx;

		.upload-placeholder {
			width: 120rpx;
			height: 120rpx;
			background-color: #cad6e8;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			border-radius: 0;

			text {
				font-size: 22rpx;
				color: #fff;
				margin-top: 4rpx;
			}

			&-hover {
				background-color: #a8b8d1;
				transform: scale(0.97);
			}
		}
	}

	// 表单项样式
	.form-item {
		display: flex;
		align-items: center;
		padding: 0 30rpx;
		min-height: 80rpx;
		background-color: #fff;
		border-bottom: 1rpx solid #f0f0f0;

		&.clickable {
			cursor: pointer;
		}

		&-hover {
			background-color: #f5f5f5;
		}

		.form-label {
			color: #333;
			font-size: 28rpx;
			flex: 1;

			&.required {
				position: relative;

				&::before {
					content: "*";
					color: red;
					position: absolute;
					left: -14rpx;
				}
			}
		}

		.form-input {
			font-size: 28rpx;
			color: #999;
			flex: 1.5;
		}

		.form-value {
			font-size: 28rpx;
			color: #666;
			flex: 1.5;
			text-align: right;

			&.price-value {
				color: #999;
			}
		}

		.value-with-arrow {
			flex: 1.5;
			display: flex;
			justify-content: flex-end;
			align-items: center;

			.form-value {
				margin-right: 10rpx;
			}
		}
	}

	// 安全库存输入
	.safe-stock-input {
		display: flex;
		justify-content: flex-end;
		align-items: center;
		flex: 1.5;

		.separator {
			margin: 0 10rpx;
			color: #999;
		}
	}

	// 备注下方的空白区域
	.remark-placeholder {
		height: 260rpx;
		background-color: #f5f7fa;
	}

	// 底部按钮
	.footer-actions {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		display: flex;
		height: 100rpx;

		.btn-continue {
			flex: 1;
			height: 100%;
			display: flex;
			justify-content: center;
			align-items: center;
			background-color: #fff;
			color: #1989fa;
			font-size: 30rpx;
			border-top: 1rpx solid #eee;

			&-hover {
				background-color: #f5f5f5;
			}
		}

		.btn-save {
			flex: 1;
			height: 100%;
			display: flex;
			justify-content: center;
			align-items: center;
			background-color: #1989fa;
			color: #fff;
			font-size: 30rpx;

			&-hover {
				background-color: #0c76d8;
				opacity: 0.9;
			}
		}
	}
</style>